/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order;

import cn.hutool.core.collection.CollUtil;
import com.lxk.oms.order.domain.bo.OmsOrderItemBo;
import com.lxk.service.pms.response.PmsProductSkuDto;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 计算积分订单的积分,必须在ORIGINAL_AMOUNT_ORDER后面
 *
 * @author heyi
 * 2024/8/21
 */
@LiteflowComponent(value = FlowOrderNodeConst.ORIGINAL_POINT_ORDER)
@AllArgsConstructor
public class OrderOriginalPointNode extends NodeComponent {
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);

    @Override
    public void beforeProcess() {
        OrderContext context = this.getContextBean(OrderContext.class);
        List<OrderContext.SkuInfo> skuInfoList = context.getSkuInfoList();
        if (CollUtil.isEmpty(skuInfoList)) {
            log.error("OrderOriginalAmountNode:{}", context);
            throw new ServiceException("商品信息为空");
        }
    }

    @Override
    public void process() throws Exception {
        OrderContext context = this.getContextBean(OrderContext.class);
        List<OrderContext.SkuInfo> skuInfoList = context.getSkuInfoList();
        List<OmsOrderItemBo> orderItemBoList = context.getOrderItemBoList();
        Map<Long, OmsOrderItemBo> orderItemBoMap = orderItemBoList.stream().collect(Collectors.toMap(OmsOrderItemBo::getSkuId, v -> v));
        skuInfoList.forEach(item -> {
            Integer count = item.getCount();
            List<PmsProductSkuDto> pmsProductSkuDtoList = item.getPmsProductSkuDtoList();
            PmsProductSkuDto pmsProductSkuDto = pmsProductSkuDtoList.get(0);
            // 积分
            BigDecimal orderPoint = pmsProductSkuDtoList.stream().map(PmsProductSkuDto::getPoint).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            // 总积分
            BigDecimal totalOrderPoint = orderPoint.multiply(new BigDecimal(count));
            context.addPayPoint(totalOrderPoint);
            OmsOrderItemBo orderItemBo = orderItemBoMap.get(pmsProductSkuDto.getId());
            orderItemBo.setPoint(orderPoint);
            orderItemBo.setTotalPoint(totalOrderPoint);
        });
    }

    @Override
    public boolean isAccess() {
        OrderContext context = this.getContextBean(OrderContext.class);
        return context.getNeedStock();
    }
}
